package com.ply.service.impl;


import com.ply.dao.PermissionDao;
import com.ply.dao.RolePermissionDao;
import com.ply.dao.UserDao;
import com.ply.dao.UserRoleDao;
import com.ply.pojo.Permission;
import com.ply.pojo.RolePermission;
import com.ply.pojo.User;
import com.ply.pojo.UserRole;
import com.ply.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private PermissionDao permissionDao;




    @Override
    public List<Permission> findPermissionByUsername(String username){
        //通过用户名查询用户
        User user = userDao.findByUsername(username);
        //通过对象查询用户角色集合
        List<UserRole> userRoles = userRoleDao.findAllByUserid(user.getId());
        //获取用户下所有的角色id
        List<Integer> userIdList = userRoles.parallelStream().map(UserRole::getId).collect(Collectors.toList());
        //获取用户下的所有角色集合
        List<UserRole> userRoleList = userRoleDao.findAllById(userIdList);
        //获取所有角色集合的rid集合
        List<Integer> list = userRoleList.parallelStream().map(UserRole::getRoleid).collect(Collectors.toList());
        //通过rid集合 获取permission集合
        List<RolePermission> rolePermissions = rolePermissionDao.findAllByRid(list);
        //获取RolePermission表的pid集合
        List<Integer> pidList = rolePermissions.parallelStream().map(RolePermission::getPid).collect(Collectors.toList());
        //获取用户下的Permission集合表
        List<Permission> permissions = permissionDao.findAllById(pidList);
        return permissions;
    }

    @Override
    public boolean isQuanxian(String username, String permissionname) {
        //调用查询用户的方法
        List<Permission> permissions = this.findPermissionByUsername(username);
        //遍历permissions集合
        List<String> permissionList = permissions.parallelStream().map(Permission::getPermissionname).collect(Collectors.toList());
        if (permissionList.contains(permissionname)){
            System.out.println("该用户>>>>"+username+">>>>>有>>>>>>"+permissionname+">>>>>>>>权限");
            return true;
        }
        else {
            System.out.println("该用户>>>>"+username+">>>>>>没有>>>>>>"+permissionname+">>>>>>>>权限");
            return false;
        }

    }


}

